<template>
  <div class="login">
    <div class="logo">
      <img src="../../deps/public/login-img1.png" />
      <p>「凯普奇」致力于打造</p>
      <p>"全生命周期的数智化管理"服务平台，</p>
      <p>提供"设备市场"行业生态与系统的整体解决方案。</p>
    </div>
    <div class="main">
      <div class="main-center">
        <div class="login-type">
          <img src="../../deps/public/runyiLogo.png" />
          凯普奇网络资源管理系统
        </div>
        <div class="login-form">
          <el-form :model="userData" :rules="rules" ref="ruleform">
            <el-form-item prop="userName">
              <el-input @keydown.enter.native="login" v-model="userData.userName" type="text" placeholder="请输入账号或手机号" suffix-icon="el-icon-user"> </el-input>
            </el-form-item>
            <el-form-item prop="pwd">
              <el-input @keydown.enter.native="login" v-model="userData.pwd" type="password" show-password placeholder="请输入密码" suffix-icon="el-icon-lock"> </el-input>
            </el-form-item>
            <el-form-item prop="imageCode" class="code-item">
              <el-input 
                v-model="userData.imageCode" 
                placeholder="请输入图片验证码"
                @keydown.enter.native="login"
              >
                <template slot="append">
                  <img 
                    :src="imageSrc" 
                    class="code-image" 
                    @click="refreshImageCode"
                  />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="authCode" class="code-item" v-if="needSmsCode">
              <el-input 
                v-model="userData.authCode" 
                placeholder="请输入短信验证码"
                @keydown.enter.native="login"
              >
                <template slot="append">
                  <el-button 
                    :disabled="sendAuthCode" 
                    @click="send"
                  >
                    {{ sendAuthCode ? `${auth_time}s后重新获取` : '获取验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="" label-width="70px" prop="loginType">
              <el-radio-group v-model="userData.tenantId">
                <el-radio :label="'JYCATV'">数据源1</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="login">立即登录</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div class="footer">
      <span><a href="https://beian.miit.gov.cn/" target="_blank">鄂ICP备13005555号-1</a></span>
    </div>
  </div>
</template>

<script>
import { loginIn, getSysMapInfoApi } from '@/deps/api'
import { setAppData, sessionStorage } from '@/deps/utils'
import { get } from 'lodash'

export default {
  data() {
    return {
      auth_time: 60,
      sendAuthCode: false,
      needSmsCode: false,
      imageSrc: '',
      userData: {
        tenantId: 'JYCATV',
        userName: 'CAPTURE',
        pwd: 'CAPTURE',
        webmoduleId: 30,
        imageCode: '',
        authCode: ''
      },
      rules: {
        userName: [{ required: true, message: '请输入账号', trigger: ['change', 'blur'] }],
        pwd: [{ required: true, message: '请输入密码', trigger: ['change', 'blur'] }],
        imageCode: [{ required: true, message: '请输入图片验证码', trigger: ['change', 'blur'] }],
        authCode: [{ required: true, message: '请输入短信验证码', trigger: ['change', 'blur'] }]
      }
    }
  },
  methods: {
    // 刷新图片验证码
    refreshImageCode() {
      // 这里使用时间戳作为随机数生成新的验证码图片
      this.imageSrc = `data:image/svg+xml;base64,${this.generateImageCode()}`
    },

    // 生成随机验证码图片
    generateImageCode() {
      // 生成4位随机数字验证码
      const code = Math.random().toString().slice(2, 6)
      // 保存验证码用于验证
      this.correctImageCode = code

      // 生成简单的 SVG 验证码图片
      const svg = `
        <svg xmlns="http://www.w3.org/2000/svg" width="100" height="40">
          <rect width="100%" height="100%" fill="#f0f2f5"/>
          <text x="50%" y="50%" dy=".3em" 
            fill="#333" font-size="24" 
            text-anchor="middle" 
            font-family="Arial, sans-serif"
            letter-spacing="4"
          >${code}</text>
        </svg>
      `
      return btoa(svg)
    },

    // 发送短信验证码
    send() {
      if (!this.userData.userName) {
        this.$message.error('请输入手机号')
        return
      }

      // 验证图片验证码
      if (this.userData.imageCode.toUpperCase() !== this.correctImageCode) {
        this.$message.error('图片验证码错误')
        return
      }

      this.sendAuthCode = true
      // 倒计时开始
      this.auth_time = 60
      const authTimer = setInterval(() => {
        this.auth_time--
        if (this.auth_time <= 0) {
          this.sendAuthCode = false
          clearInterval(authTimer)
        }
      }, 1000)

      // 这里模拟发送验证码成功
      this.$message.success('验证码发送成功')
      // 保存正确的验证码（实际项目中应该由后端处理）
      this.correctAuthCode = '123456'
    },

    login() {
      this.$refs['ruleform'].validate(valid => {
        if (valid) {
          // 验证图片验证码
          if (this.userData.imageCode.toUpperCase() !== this.correctImageCode) {
            this.$message.error('图片验证码错误')
            return
          }

          // 如果需要短信验证码，则验证
          if (this.needSmsCode && this.userData.authCode !== this.correctAuthCode) {
            this.$message.error('短信验证码错误')
            return
          }

          setAppData('$defaultRequestHeader', { tenantId: this.userData.tenantId })
          loginIn(this.userData).then(res => {
            const userData = {
              Authorization: res.Authorization,
              entities: res.entities,
              ...this.userData
            }
            sessionStorage('userData', userData)
            setAppData('$defaultRequestHeader', { Authorization: res.Authorization })
            // 获取地图信息
            getSysMapInfoApi({webmoduleId: 60}).then(res => {
              sessionStorage('sysMapInfo', res)
            })
            // 获取默认菜单并设置第一个页签
            const menu = get(userData, 'entities[0].menus[0]', {})
            const firstTab = {
              title: menu.menuName || '首页',
              path: `/${menu.menuUrl || 'designIndex'}`,
              name: menu.menuUrl || 'designIndex'
            }
            // 保存第一个页签
            sessionStorage('breadcrumbs', [firstTab])
            // 触发菜单变更事件
            this.$bus.$emit('CHANGE_MENU', menu.csysMenuId)
            // 路由跳转
            this.$router.push({ name: menu.menuUrl || 'designIndex' })
          }, () => {
            this.refreshImageCode()
          })
        }
      })
    }
  },
  created() {
    // 清除所有 sessionStorage
    window.sessionStorage.clear()
    // 触发登出事件，确保页签被清除
    window.localStorage.clear()
    setAppData('$defaultRequestHeader', { Authorization: '' })
    this.$bus.$emit('USER_LOGOUT')
    // 生成初始图片验证码
    this.refreshImageCode()
  }
}
</script>

<style lang="scss">
.login {
  width: 100%;
  height: 100%;
  position: relative;
  background: url('../../deps/public/loginBg.png') no-repeat;
  background-size: cover;
  
  .logo {
    position: absolute;
    left: 160px;
    top: 50%;
    transform: translate(0%, -50%);
    color: var(--text-color);
    
    img {
      width: 500px;
      margin-bottom: 20px;
    }
    
    p {
      font-size: 16px;
      line-height: 24px;
    }
  }
  
  .main {
    width: 400px;
    position: absolute;
    right: 100px;
    top: 50%;
    transform: translate(0%, -50%);
    background: #fff;
    border-radius: 4px;
    padding: 40px;
    
    &-center {
      margin: 1rem auto;
    }
  }
  
  .login-type {
    overflow: hidden;
    margin-bottom: 2rem;
    text-align: center;
    font-size: 24px;
    
    span {
      display: block;
      width: 100%;
      height: 40px;
      float: left;
      font-size: 16px;
      text-align: center;
      color: #ccc;
      cursor: pointer;
    }
    
    .active {
      color: rgb(124, 207, 194);
      border-bottom: 2px solid rgb(124, 207, 194);
    }
  }
  
  .login-form {
    .el-form-item {
      margin-bottom: 2rem;
      
      .el-button {
        width: 100%;
        border: 0;
      }
    }
    
    .usercode {
      .el-input {
        width: 59%;
      }
      
      .el-button {
        float: right;
        width: 40%;
        background: #FFF;
      }
    }

    .code-item {
      .el-input-group__append {
        padding: 0;
        overflow: hidden;
        
        .code-image {
          height: 36px;
          margin: -1px;
          cursor: pointer;
        }
        
        .el-button {
          margin: 0;
          border: none;
          padding: 12px 15px;
          
          &:hover {
            background: var(--color-primary-light);
            color: #fff;
          }
        }
      }
    }
  }
}

.footer {
  width: 50%;
  position: absolute;
  bottom: 20px;
  right: 0;
  text-align: center;
  font-size: 14px;
  z-index: 999;
  span {
    padding: 0 4px;
  }
  a {
    color: rgba(0,0,0,0.65);
  }
}
</style>
